package com.xyzwps.ewa.modules

import com.xyzwps.ewa.common.ServerException
import com.xyzwps.ewa.modules.auth.authRoutes
import com.xyzwps.ewa.modules.demo.demoRoutes
import com.xyzwps.ewa.modules.global.globalRoutes
import com.xyzwps.ewa.modules.me.meRoutes
import com.xyzwps.ewa.modules.user.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable

fun Application.useRoutes() {
    install(StatusPages) {
        exception<Throwable>(handler = ::errorHandler)
    }
    routing {
        route("/apis/demo") { demoRoutes() }
        route("/apis/auth") { authRoutes() }
        route("/apis/global") { globalRoutes() }
        route("/apis/me") { meRoutes() }
        route("/apis/users") { userRoutes() }
    }
}


suspend fun errorHandler(call: ApplicationCall, cause: Throwable) {
    if (cause is ServerException) {
        call.respond(cause.status, ErrorInfo(cause.message ?: "Unhandled Error"))
    } else {
        call.respond(HttpStatusCode.InternalServerError, INTERNAL_SERVER_ERROR)
    }
}

@Serializable
data class ErrorInfo(val message: String)

val INTERNAL_SERVER_ERROR = ErrorInfo("Internal Server Error")